package net.wanho.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.constant.UserConstant;
import net.wanho.dto.LoginUserDTO;
import net.wanho.exception.CaptchaException;
import net.wanho.exception.LoginErrorException;
import net.wanho.mapper.UserMapper;
import net.wanho.po.User;
import net.wanho.service.CaptchaService;
import net.wanho.service.LoginService;
import net.wanho.util.JwtUtil;
import net.wanho.util.PwdUtil;
import net.wanho.vo.LoginUserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2024-08-19 15:59
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final CaptchaService captchaService;
    private final UserMapper userMapper;

    @Override
    public LoginUserVo login(LoginUserDTO loginUserDTO) {
        // 判断验证码
        try {
            captchaService.check(loginUserDTO.getUuid(), loginUserDTO.getCode());
        } catch (RuntimeException e) {
            throw new CaptchaException(e.getMessage());
        }

        // 判断用户
        User user = userMapper.selectByUsername(loginUserDTO.getUsername());
        if (ObjectUtils.isEmpty(user)){
            throw new LoginErrorException("用户不存在！");
        }
        if (!user.getPassword().equals(PwdUtil.encrypt(loginUserDTO.getPassword()))){
            throw new LoginErrorException("密码不正确！");
        }
        if(user.getStatus()== UserConstant.STATUS_DISABLE){
            throw new LoginErrorException("用户被禁用！");
        }

        // 生成token
        Map<String,Object> payload = new HashMap<>();
        payload.put("id", user.getId());
        payload.put("username", user.getUsername());
        String token = JwtUtil.generate(payload);

        // 返回用户信息
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(user.getId());
        loginUserVo.setUsername(user.getUsername());
        loginUserVo.setToken("Bearer " + token);

        return loginUserVo;
    }
}
